/**
 * Created by zhuminghua on 14-4-17.
 */
define(function () {

    function UserNew(options) {
        this.init(options);
    }

    UserNew.prototype = {

        init: function (options) {
            this.options = options;
        },
        setOptions: function (options) {
            this.options = $.extend(this.options, options);
        },
        show: function () {
            $("div[data-sign=content]").hide();
            $("#content_user_edit").show();
            this.loadContent();
        },
        loadContent: function () {
            var that = this;
            var url = this.options.host + "/system/user/page/userNew";
            var params = {id: this.options.id};
            $("#div_user_edit").empty();
            $("#div_user_edit").block({message: "Loading..."});
            $("#div_user_edit").load(url + " #form_user", params, function (responseText, textStatus, XMLHttpRequest) {
                $("#div_user_edit").unblock();
                that.loadContentFinish();
            });
        },
        loadContentFinish: function () {
            // 初始化UI组件
            //App.initUniform();
            Apps.reloadUniform();
            // 初始化事件
            this.initEvents();
            // 初始化校验组件
            this.initValidate();
            this.initAppTree({
                id: this.options.id,
                url: this.options.host
            });
        },
        initEvents: function () {
            var that = this;
            $("#btn_user_save").off("click").on("click", function () {
                that.btnSave();
            });
            $("#btn_user_back").off("click").on("click", function () {
                that.btnBack();
            });
        },
        initValidate: function () {
            $('#form_user').bootstrapValidator({
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    loginName: {
                        message: '',
                        validators: {
                            notEmpty: {
                                message: '登录名不能为空'
                            }
                        }
                    },
                    userName: {
                        message: '',
                        validators: {
                            notEmpty: {
                                message: '用户名不能为空'
                            }
                        }
                    },
                    roles: {
                        message: '',
                        validators: {
                            notEmpty: {
                                message: '必须选择至少一个角色'
                            }
                        }
                    },

                }
            });
            this.validate = $('#form_user').data('bootstrapValidator');
        },
        initAppTree: function (data) {
            var url = data.url + "/system/user/getAppTree?id=" + data.id;

            //$("div[data-sign=content]").hide();

            //$("#btn_user_save").attr("disabled", false);
            //$("#btn_user_save").off("click.role_authorize").on("click.role_authorize", function () {
            //    $("#role_authorize_funcIds").val();
            //    $("#role_authorize_id").val(data.id);
            //    that.btnSave_authorize(data.type);
            //});

            /*$("#btn_role_authorize_back").off("click.role_authorize").on("click.role_authorize", function () {
             that.btnBack_authorize();
             });*/

            var that = this;
            if (this.dynatree) {
                //$("#div_role_authorize").dynatree("getTree").reload();
                //$('#div_role_authorize').dynatree('destroy');
            }
            this.dynatree = $("#div_role_authorize").dynatree({
                checkbox: true,
                imagePath: "skin-custom/",
                selectMode: 3,
                minExpandLevel: 3,
                initAjax: {
                    url: url
                },
                onSelect: function (select, node) {
                    // Get a list of all selected nodes, and convert to a key array:
                    var selKeys = $.map(node.tree.getSelectedNodes(), function (node) {
                        return node.data.key;
                    });
                    $("#appId").val(selKeys);
                },
                onDblClick: function (node, event) {
                    node.toggleSelect();
                },
                onKeydown: function (node, event) {
                    if (event.which == 32) {
                        node.toggleSelect();
                        return false;
                    }
                },
                // The following options are only required, if we have more than one tree on one page:
                initId: "treeData",
                cookieId: "dynatree-Cb3",
                idPrefix: "dynatree-Cb3-",
                selectMode: 1,
                // minExpandLevel: 0,
                debugLevel: 0
            });
        },
        getFormData: function () {
            var data = {};
            // 获取表单的值
            $("#form_user").find("input[type=hidden],input[type=text],input[type=password],textarea,select").each(function () {
                data[this.name] = $(this).val();
            });
            // 获取多选的角色
            var roles = [];
            $("#form_user input[name=roles]:checked").each(function () {
                roles.push($(this).val());
            });
            data["roles"] = roles.join(",");
            return data;
        },
        btnSave: function () {
            if (!this.validate.isValid()) {
                return;
            }
            var that = this;

            $("#btn_user_save").attr("disabled", true);
            // 保存请求
            $.ajax({
                url: that.options.host + "/system/user/userSave",
                type: "post",
                data: that.getFormData(),
                success: function (data) {
                    $("#btn_user_save").attr("disabled", false);
                    if (data.rsCode == "A00000") {
                        $.gritter.add({title: "提示信息：", text: "保存成功！", time: 1000});
                        if ($.isFunction(that.options.callback_btnSave)) {
                            that.options.callback_btnSave(data);
                        }
                    } else {
                        $.gritter.add({title: "提示信息：", text: data.rsMsg, time: 2000});
                    }
                }
            });
        },
        btnBack: function () {
            $("div[data-sign=content]").hide();
            $("#content_user_list").show();
            if ($.isFunction(this.options.callback_btnBack)) {
                this.options.callback_btnBack();
            }
        }
    };

    return UserNew;

});